package priv.sympsel.multiThreadDemo;

import org.junit.Test;

class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("i: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

public class MyTest {
    @Test
    public void test1() {
        Thread myThread = new MyThread();
        // start 创建线程
        myThread.start();
        // run 未创建线程，仅仅只是调用
//        myThread.run();

        for (int j = 0; j < 100; j++) {
            System.out.println("j: " + j);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Test
    public void test2() {
        Thread myThread = new Thread(new MyRunnable());
        myThread.start();
    }

    @Test
    public void test3() {
        Thread th = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("i: " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("th thread over");
        }, "th");
        th.start();
        for (int j = 0; j < 100; j++) {
            System.out.println("j: " + j);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("main thread over");
    }

    @Test
    public void test4() {
        Runnable runnable = () -> {
            for (int i = 0; i < 3; i++) {
                try {
                    System.out.println("xxx");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        for (int i = 0; i < 2; i++) {
            try {
                Thread.sleep(1000);
                System.out.println(i);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        Thread thread1 = new Thread(runnable);
        thread1.start();
        System.out.println(thread1.isAlive());
    }

}
